﻿using System;
using System.Data;
using System.Collections.Generic;
using Maticsoft.Common;
using jutehui.Model;
using jutehui.DALFactory;
using jutehui.IDAL;
using System.Linq;

namespace jutehui.BLL
{
    /// <summary>
    /// Product
    /// </summary>
    public partial class Product
    {
        private readonly IProduct dal = DataAccess.CreateProduct();
        //设置定时器
        System.Timers.Timer timer = new System.Timers.Timer(1000 * 60);
        private int _startHot = 0;
        public Product()
        {
        }
        #region  BasicMethod

        /// <summary>
        /// 得到最大ID
        /// </summary>
        public int GetMaxId()
        {
            return dal.GetMaxId();
        }

        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int ProductId)
        {
            return dal.Exists(ProductId);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public long Add(jutehui.Model.Product model)
        {
            return dal.Add(model);
        }
        /// <summary>
        /// 整张表数据插入数据库
        /// </summary>
        /// <param name="Tname"></param>
        /// <param name="dt"></param>
        /// <param name="exm"></param>
        /// <returns></returns>
        public bool SaveTableData(string Tname, DataTable dt, out string exm)
        {
            //string CacheKey = "ProductList";
            //Maticsoft.Common.DataCache.DeleCacheByKey(CacheKey);

            return dal.SaveTableData(Tname, dt, out exm);
        }
        /// <summary>
        /// 整张表数据插入数据库  淘宝特卖 九块九
        /// </summary>
        /// <param name="Tname"></param>
        /// <param name="dt"></param>
        /// <param name="exm"></param>
        /// <returns></returns>
        public bool SaveTableDataTmallToSql(string Tname, DataTable dt, out string exm, string isTmall)
        {
            //string CacheKey = "ProductList";
            //Maticsoft.Common.DataCache.DeleCacheByKey(CacheKey);

            return dal.SaveTableDataTmall(Tname, dt, out exm, isTmall);
        }

        /// <summary>
        /// 小时榜数据保存
        /// </summary>
        /// <param name="Tname"></param>
        /// <param name="dt"></param>
        /// <param name="exm"></param>
        /// <returns></returns>
        public bool SaveHourTopData(string Tname, DataTable dt, out string exm)
        {
            return dal.SaveTableDataToHourTop(Tname, dt, out exm);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(jutehui.Model.Product model)
        {
            return dal.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(long ProductId)
        {

            return dal.Delete(ProductId);
        }
        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool DeleteList(string ProductIdlist)
        {
            return dal.DeleteList(Maticsoft.Common.PageValidate.SafeLongFilter(ProductIdlist, 0));
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public jutehui.Model.Product GetModel(int ProductId)
        {

            return dal.GetModel(ProductId);
        }

        /// <summary>
        /// 得到一个对象实体，从缓存中
        /// </summary>
        public jutehui.Model.Product GetModelByCache(int ProductId)
        {

            string CacheKey = "ProductModel-" + ProductId;
            object objModel = Maticsoft.Common.DataCache.GetCache(CacheKey);
            if (objModel == null)
            {
                try
                {
                    objModel = dal.GetModel(ProductId);
                    if (objModel != null)
                    {
                        int ModelCache = Maticsoft.Common.ConfigHelper.GetConfigInt("ModelCache");
                        Maticsoft.Common.DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero);
                    }
                }
                catch { }
            }
            return (jutehui.Model.Product)objModel;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            return dal.GetList(strWhere);
        }
        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int Top, string strWhere, string filedOrder)
        {
            return dal.GetList(Top, strWhere, filedOrder);
        }
        public void StartSetCacheTimer()
        {
            //定义风云榜商品参数
            timer.Elapsed += new System.Timers.ElapsedEventHandler(ResetCache);
            timer.AutoReset = true;//一直执行
            timer.Enabled = true;
        }
        /// <summary>
        /// 设置 这个时间段重置缓存
        /// </summary>
        /// <param name="source"></param>
        /// <param name="e"></param>
        public void ResetCache(object source, System.Timers.ElapsedEventArgs e)
        {
            int minit = DateTime.Now.Minute;
            if ((minit >= 0 && minit < 4) || _startHot == 0)
            {
                string CacheKey = "ProductList";
                Maticsoft.Common.DataCache.DeleCacheByKey(CacheKey);
                var objList = GetModelList(" TypeId=0  and DeleteTime is null");
                if (objList != null)
                {
                    int ModelCache = Maticsoft.Common.ConfigHelper.GetConfigInt("ModelCache");
                    Maticsoft.Common.DataCache.SetCache(CacheKey, objList, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero);
                }
                _startHot = 1;
            }
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<jutehui.Model.Product> GetModelListByCache(ref string msg, DateTime dtime)
        {
            //string CacheKey = "ProductList";
            //object objList = Maticsoft.Common.DataCache.GetCache(CacheKey);
            //if (objList == null)
            //{
            //    try
            //    {
            //        objList = GetModelList(" TypeId=0  and DeleteTime is null");
            //        if (objList != null)
            //        {
            //            int ModelCache = Maticsoft.Common.ConfigHelper.GetConfigInt("ModelCache");
            //            Maticsoft.Common.DataCache.SetCache(CacheKey, objList, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero);
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        msg = "Product:GetModelListByCache:" + ex.Message.ToString();
            //    }
            //}UpdateTime <= FirstDateTime.AddHours(1) && o.UpdateTime >= FirstDateTime)

            List<jutehui.Model.Product> list = GetModelList(" TypeId=0  and DeleteTime is null and UpdateTime<='" + dtime.AddHours(1) + "' and UpdateTime>='" + dtime + "'");

            return list;
        }
        /// <summary>
        /// 获取最新数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<jutehui.Model.Product> GetNewData(int id)
        {
            List<jutehui.Model.Product> list = GetModelList(" TypeId=1 and ProductId>" + id + " order by ProductId desc");
            return list;

        }

        ///// <summary>
        ///// 保存到数据库是 并写到缓存里
        ///// </summary>
        //public bool SaveModelListByCache(ref string msg)
        //{
        //    string CacheKey = "ProductList";
        //    object objList = null;
        //    try
        //    {
        //        objList = dal.GetList(" TypeId=0 ");
        //        if (objList != null)
        //        {
        //            Maticsoft.Common.DataCache.DeleCacheByKey(CacheKey);
        //            int ModelCache = Maticsoft.Common.ConfigHelper.GetConfigInt("ModelCache");
        //            Maticsoft.Common.DataCache.SetCache(CacheKey, objList, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero);
        //            return true;
        //        }
        //        msg = "SaveModelListByCache：没有查找到风云榜数据";

        //        return false;
        //    }
        //    catch (Exception ex)
        //    {
        //        msg = "SaveModelListByCache:" + ex.Message.ToString();
        //        return false;
        //    }
        //}

        /// <summary>
        /// 从数据库中获取指定数量的数据
        /// </summary>
        public List<jutehui.Model.Product> GetProductByPage(int lastId, int pageSize)
        {
            string whereStr = " 1=1 ";
            //从数据库中获取数据 
            List<jutehui.Model.Product> proList = new List<jutehui.Model.Product>();
            proList = GetListByPage(whereStr, lastId, pageSize);
            return proList;
        }


        /// <summary>
        /// 从数据库中获取指定页数的数据
        /// </summary>
        public List<jutehui.Model.Product> GetPageModelListByCache(int navigationId, int lastId, int pageSize, string name, string typeId, string sourceID)
        {
            string whereStr = " 1=1 ";
            //从数据库中获取数据
            //  var list = GetModelList("");
            List<jutehui.Model.Product> proList = new List<jutehui.Model.Product>();
            //if (list == null)
            //{
            //    return null;
            //} 
            var keyName = name.Split('|').ToList();
            if (lastId == 0) //第一次加载返回所有数据
            {
                //搜索内容不为空时 查找部分类型所有数据
                if (name == "" && typeId == "" && sourceID == "")
                {

                    whereStr += " and T.TypeId=" + navigationId;
                }
                //else if (name != "" && typeId == "" && sourceID == "")
                //{
                //    whereStr = "Pname like '%" + name + "%'";
                //}
                //else if (name == "" && typeId != "" && sourceID == "")
                //{
                //    whereStr = "ProductTypeId=" + typeId;
                //}
                //else if (name == "" && typeId == "" && sourceID != "")
                //{
                //    whereStr = "Memo like '%" + sourceID + "%'";
                //}

                if (name != "")
                {
                    whereStr += " and (";
                    for (int index = 0; index < keyName.Count-1; index++)
                    {
                        whereStr += "T.Pname like '%" + keyName[index] + "%' or ";
                    }
                    whereStr += "  T.Pname like '%" + keyName[keyName.Count - 1] + "%')";
                }
                if (typeId != "")
                {
                    whereStr += " and T.ProductTypeId=" + typeId;
                }
                if (sourceID != "")
                {
                    whereStr += " and T.Memo like '%" + sourceID + "%'";
                }

            }
            else if (lastId != 0)
            {
                if (name == "" && typeId == "" && sourceID == "")
                {
                    whereStr += " and T.TypeId=" + navigationId + " and T.ProductId<" + lastId;
                }
                if (name != "")
                {
                    whereStr += " and (";
                    for (int index = 0; index < keyName.Count - 1; index++)
                    {
                        whereStr += "T.Pname like '%" + keyName[index] + "%' or ";
                    }
                    whereStr += "  T.Pname like '%" + keyName[keyName.Count - 1] + "%') and T.ProductId<" + lastId;
                   // whereStr += " and T.Pname like '%" + name + "%'  and T.ProductId<" + lastId;
                }
                if (typeId != "")
                {
                    whereStr += " and T.ProductTypeId =" + typeId + " and T.ProductId<" + lastId;
                }
                if (sourceID != "")
                {
                    whereStr += " and T.Memo like '%" + sourceID + "%' and T.ProductId<" + lastId;
                }
                //else if (name != "" && typeId == "" && sourceID == "")
                //{
                //    whereStr = "Pname like '%" + name + "%'  and T.ProductId<" + lastId;

                //}
                //else if (name == "" && typeId != "" && sourceID == "")
                //{
                //    whereStr = "ProductTypeId =" + typeId + " and T.ProductId<" + lastId;

                //}
                //else if (name == "" && typeId == "" && sourceID != "")
                //{
                //    whereStr = "Memo like '%" + sourceID + "%' and T.ProductId<" + lastId;
                //}
            }
            proList = GetListByPage(whereStr, lastId, pageSize);
            return proList;
        }
        /// <summary>
        /// 从数据库中获取指定页数的数据  九块九
        /// </summary>
        public List<jutehui.Model.Product> GetjiukuaijiuProducts(int lastId, int pageSize, string topPrice, string downPrice, string categoryId)
        {
            string whereStr = "";
            //从数据库中获取数据
            //  var list = GetModelList("");
            List<jutehui.Model.Product> proList = new List<jutehui.Model.Product>();

            if (lastId == 0) //第一次加载返回所有数据
            {
                //搜索内容不为空时 查找部分类型所有数据
                if (topPrice == "" && categoryId == "")//全部分类全部价格数据
                {
                    whereStr = "T.TypeId=3";
                }
                else if (topPrice != "" && categoryId == "")//全部分类中按价格分类-------
                {
                    whereStr = "cast (T.Price as decimal(12,2)) >=" + downPrice + " and cast (T.Price as decimal(12,2))<=" + topPrice;
                }
                else if (topPrice == "" && categoryId != "")
                {
                    whereStr = "T.secondCategoryId=" + categoryId;
                }
                else if (topPrice != "" && categoryId != "")
                {
                    whereStr = "cast (T.Price as decimal(12,2)) >" + downPrice + " and cast (T.Price  as decimal(12,2))<=" + topPrice + " and T.secondCategoryId=" + categoryId;
                }
                else
                {
                    whereStr = "T.TypeId=3";
                }
            }
            else if (lastId != 0)
            {
                //搜索内容不为空时 查找部分类型所有数据
                if (topPrice == "" && categoryId == "")//全部分类全部价格数据
                {
                    whereStr = "T.TypeId=3  and T.ProductId<" + lastId;
                }
                else if (topPrice != "" && categoryId == "")//全部分类中按价格分类-------
                {
                    whereStr = "cast (T.Price as decimal(12,2)) >=" + downPrice + " and cast (T.Price  as decimal(12,2))<=" + topPrice + " and T.ProductId<" + lastId; ;
                }
                else if (topPrice == "" && categoryId != "")
                {
                    whereStr = "T.secondCategoryId=" + categoryId + " and T.ProductId<" + lastId; ;
                }
                else if (topPrice != "" && categoryId != "")
                {
                    whereStr = "cast (T.Price as decimal(12,2)) >=" + downPrice + " and cast (T.Price as decimal(12,2))<=" + topPrice + " and T.secondCategoryId=" + categoryId + " and T.ProductId<" + lastId; ;
                }
                else
                {
                    whereStr = "T.TypeId=3  and T.ProductId<" + lastId;
                }
            }
            proList = GetListFromTeMai(whereStr, lastId, pageSize);
            return proList;
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<jutehui.Model.Product> GetModelList(string strWhere)
        {
            DataSet ds = dal.GetList(strWhere);
            return DataTableToList(ds.Tables[0]);
        }
        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<jutehui.Model.Product> DataTableToList(DataTable dt)
        {
            List<jutehui.Model.Product> modelList = new List<jutehui.Model.Product>();

            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                jutehui.Model.Product model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = dal.DataRowToModel(dt.Rows[n]);
                    if (model != null)
                    {
                        modelList.Add(model);
                    }
                }
            }
            return modelList;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetAllList()
        {
            return GetList("");
        }

        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            return dal.GetRecordCount(strWhere);
        }
        /// <summary>
        /// 分页获取数据列表 无查询条件
        /// </summary>
        private List<jutehui.Model.Product> GetListByPage(string where, int productId, int pageSize)
        {
            DataSet result = dal.GetListByPage(where, productId, pageSize);

            return DataTableToList(result.Tables[0]);
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public List<jutehui.Model.Product> GetListFromTeMai(string strWhere, int productId, int pageSize)
        {
            DataSet result = dal.GetListByPageTeMai(strWhere, productId, pageSize);

            return DataTableToList(result.Tables[0]);
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        //public DataSet GetList(int PageSize,int PageIndex,string strWhere)
        //{
        //return dal.GetList(PageSize,PageIndex,strWhere);
        //}

        #endregion  BasicMethod
        #region  ExtensionMethod

        #endregion  ExtensionMethod
    }
}

